<script setup>
import { ref } from 'vue';
import { wxMiniGetPhoneNumber } from '@/api/login';
import Toast from '@vant/weapp/dist/toast/toast';

const show = ref(false);
const userStore = {};

const rules = {
    phone: [
        { required: true, message: '手机号不能为空', trigger: ['blur', 'change'] },
        { pattern: /^1[3456789]\d{9}$/, message: '手机号格式不正确', trigger: ['blur', 'change'] }
    ],
    smsCode: [
        { required: true, message: '验证码不能为空', trigger: ['blur'] }
    ]
};
const info = ref({
    phone: '',
    code: '',
    smsCode: '',
});
const formRef = ref(null);

const countdown = ref(60);
const timer = ref(null);
const timerCodeText = ref('获取验证码');
const imgCodeAlertShow = ref(false);
const isDisabled = ref(false);

const current = ref(0); // swiper选中

async function getPhoneNumber(e) {
    if (e.detail.code) {
        const res = await wxMiniGetPhoneNumber({
            unionId: userStore.userInfo.unionId,
            code: e.detail.code,
        });
        if (res.data) {
            setToken(res.data.token);
        }
        show.value = false;
        Toast.showSuccessToast('绑定成功');
        await userStore.getUserInfoFn();
    }
}

function toggleFn() {
    current.value = 1;
}

function showBingPhone() {
    show.value = true;
    current.value = 0;
}

function closeBingPhone() {
    show.value = false;
}

async function submit() {
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    await formRef.value.validate();
    if (isDisabled.value) return;
    const res = await bindPhone(info.value);
    if (res.data) {
        setToken(res.data.token);
    }
    isDisabled.value = false;
    await userStore.getUserInfoFn();
    userStore.getStudentInfo();
    Toast.showSuccessToast('绑定成功');
    show.value = false;
    uni.redirectTo({ url: currentPage.$page.fullPath });
}

function getCode() {
    if (countdown.value !== 60) {
        return;
    }
    formRef.value.validateField('phone', (e) => {
        if (e.length === 0) {
            imgCodeAlertShow.value = true;
        }
    });
}

function startCountdown() {
    timer.value = setInterval(() => {
        if (countdown.value > 1) {
            countdown.value--;
            timerCodeText.value = `${countdown.value}秒后再试`;
        } else {
            clearInterval(timer.value);
            countdown.value = 60;
            timerCodeText.value = `获取验证码`;
        }
    }, 1000);
}

function sendBefore(e) {
    info.value.code = e;
    startCountdown();
}

defineExpose({
    showBingPhone
});
</script>

<template>
    <van-popup v-model:show="show" position="bottom" round>
        <div class="bindPhoneNumber_cop">
            <div class="title">绑定手机号</div>
            <swiper class="swiper" :current="current" @change="(e) => current = e.detail.current">
                <swiper-item class="swiper_item">
                    <div class="getPhone_box">
                        <button @getphonenumber="getPhoneNumber" open-type="getPhoneNumber" class="top_btn">
                            一键获取手机号
                        </button>
                        <div class="bom_btn" @click="toggleFn">其他手机号</div>
                    </div>
                </swiper-item>
                <swiper-item class="swiper_item">
                    <van-form ref="formRef" :model="info" :rules="rules">
                        <van-field v-model="info.phone" name="phone" label="手机号" placeholder="请输入手机号" type="tel" required />
                        <van-field v-model="info.smsCode" name="smsCode" label="验证码" placeholder="请输入验证码" type="tel"
                            required :right-icon="timerCodeText" @click-right-icon="getCode" />
                    </van-form>
                    <van-button type="primary" block @click="submit">绑定手机号</van-button>
                    <!-- #ifdef MP-WEIXIN -->
                    <button @getphonenumber="getPhoneNumber" open-type="getPhoneNumber" class="bindPhoneBtn">
                        获取微信号码
                    </button>
                    <!-- #endif -->
                </swiper-item>
            </swiper>
        </div>
    </van-popup>
</template>

<style lang='scss' scoped>
.bindPhoneNumber_cop {
    padding-top: 16px;

    .title {
        font-size: 18px;
        font-weight: bold;
        text-align: center;
        margin-bottom: 16px;
    }

    .swiper {

        .swiper_item {
            box-sizing: border-box;
            padding: 16px 16rpx 0;

        }

    }

    .getPhone_box {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 16px;

        .top_btn {
            width: 100%;
            height: 48px;
            background: #04C160;
            border-radius: 8px;
            color: #FFFFFF;
            text-align: center;
            line-height: 48px;
        }

        .bom_btn {
            width: 100%;
            height: 48px;
            background: #F0F0F0;
            border-radius: 8px;
            color: #04C160;
            text-align: center;
            line-height: 48px;
        }
    }

    .bindPhoneBtn {
        margin-top: 16px;
        color: #D72420;
        background: transparent;
        border: none;
    }
}
</style>
